package com.gl.basis.mongodb.dao;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;


import java.util.Date;
import java.util.List;

/**
 * @Author
 * @Date 2018-10-15 09:58
 */
public class BaseMongoDao {

    public <T> Query buildQuery(T t, String orderColumn, Sort.Direction direction, int page, int size) {
        return new Query(Criteria.byExample(t)).with(new PageRequest(page - 1, size))
                .with(new Sort(direction, orderColumn));
    }

    public <T> Query buildQueryDesc(T t, String orderColumn, int page, int size) {
        return buildQueryDesc(Criteria.byExample(t), orderColumn, page, size);
    }

    public Query buildQueryDesc(Criteria criteria, String orderColumn, int page, int size) {
        return new Query(criteria).with(new PageRequest(page - 1, size))
                .with(new Sort(Sort.Direction.DESC, orderColumn));
    }

    public Query buildQuery(Query query, int page, int size) {
        return query.with(new PageRequest(page - 1, size));
    }

    public Query buildOrderDesc(Query query, String orderColumn) {
        return query.with(new Sort(Sort.Direction.DESC, orderColumn));
    }

    public Query buildQueryAsc(Criteria criteria, String orderColumn, int page, int size) {
        return new Query(criteria).with(new PageRequest(page - 1, size))
                .with(new Sort(Sort.Direction.ASC, orderColumn));
    }

    public Query buildOrderAsc(Query query, String orderColumn) {
        return query.with(new Sort(Sort.Direction.ASC, orderColumn));
    }

  /*  public <T> Page<T> buildPageInfo(int page, int size, long total, List<T> logList) {
        int pages = (int) (total / size);
        if (total % size != 0) {
            pages = pages + 1;
        }

        Page pageInfo = new Page();
        pageInfo.setPageNo(page);
        pageInfo.setPageSize(size);
        pageInfo.setTotalSize(total);
        pageInfo.setPages(pages);
        pageInfo.setList(logList);
        return pageInfo;
    }*/

  

    public <T> void buildCriteria(Criteria criteria, String fieldName, T fieldValue) {
        if (!StringUtils.isEmpty(fieldValue)) {
            criteria.and(fieldName).is(fieldValue);
        }
    }

    public void buildTimeCriteria(Criteria criteria, String fieldName, Date startTime, Date endTime) {
        if (startTime != null && endTime != null) {
            criteria.and(fieldName).lte(endTime).gte(startTime);
        } else if (endTime != null) {
            criteria.and(fieldName).lte(endTime);
        } else if (startTime != null) {
            criteria.and(fieldName).gte(startTime);
        }
    }
}
